package org.ww.authserver.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.ww.authserver.dto.WeiboAccessTokenResponseDto;
import org.ww.authserver.feign.MemberFeiginClient;
import org.ww.common.constant.AuthConstant;
import org.ww.common.utils.R;
import org.ww.common.vo.MemberRespVo;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: gmall
 * @description: 登录
 * @author: ww
 * @create: 2024-05-08 10:30
 **/

@Slf4j
@Controller
public class Oauth2Controller {

    private static final String WEIBO_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";

    @Value("${oauth2.weibo.clientId}")
    private String clientId;

    @Value("${oauth2.weibo.clientSecret}")
    private String clientSecret;

    @Autowired
    private MemberFeiginClient memberFeiginClient;

    @GetMapping("/oauth2.0/weibo/success")
    public String weiboLoginCallback(@RequestParam("code") String code, HttpSession session){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("client_id",clientId);
        paramMap.put("client_secret",clientSecret);
        paramMap.put("grant_type","authorization_code");
        paramMap.put("code",code);
        paramMap.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        String post = HttpUtil.post(WEIBO_ACCESS_TOKEN_URL,paramMap);
        JSONObject response = JSON.parseObject(post);
        log.info("微博登录结果：{}",post);

        if(response.get("error_code") != null){
            //请求失败
            return "redirect:http://auth.gulimall.com/login.html";
        }else{
            //请求成功
            WeiboAccessTokenResponseDto accessTokenResponseDto = JSON.parseObject(post, WeiboAccessTokenResponseDto.class);

            //知道当前是哪个社交用户
            //1) 当前登录用户第一次登录进来，默认进行注册（为当前登录用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            R r = memberFeiginClient.weiboLogin(accessTokenResponseDto);
            if(r.getCode() == 0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                //使用session共享方案：将所有session存在公共区域，无论扩展服务还是安全问题都能得到保障
                //但是存在不同域名之间session不共享的问题:使用子域名的方式进行解决
                //序列化问题：现在默认使用的jdk序列化机制
                //TODO 1:默认发的卡是 session=adfdaf 作用域默认是当前域，无法解决子域名session共享问题
                //TODO 2:redis中使用JSON的序列化方式来进行序列化
                session.setAttribute(AuthConstant.LONGINUSER,data);
                log.info("登录成功:{}",data);
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }
    }



}
